from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.settings import api_settings
from rest_framework.exceptions import APIException
from .models import Userinfo
import jwt

jwt_decode_handler = api_settings.JWT_DECODE_HANDLER


class JwtAuth(BaseAuthentication):
    def authenticate(self, request):
        try:
            token = request.META.get('HTTP_TOKEN')
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            raise APIException('身份信息已过期')
        except jwt.DecodeError:
            raise APIException('身份信息验证失败')
        except jwt.InvalidTokenError:
            raise APIException('身份信息有误')
        user = Userinfo.objects.filter(pk=payload.get('user_id')).first()
        return user, token

